package sample.crawler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import sample.crawler.base.BaseTask;
import sample.enums.MapType;
import sample.model.Company;
import sample.utils.IndexUtils;
import sample.utils.StringUtils;

public class GaodeTask extends BaseTask {


    public GaodeTask()
    {
        super.mapCode = MapType.gaode.getCode();
    }
    public GaodeTask(String url)
    {
        super.mapCode = MapType.gaode.getCode();
        this.url = url;
    }

    @Override
    public String getUrl(Integer pageNo) {
        //return "https://restapi.amap.com/v3/place/text?key=3ad6adff282cd478c85c743b1f795b80&keywords=" + keywords + "&city=" + area + "&output=json&offset="+pageSize+"&page=" + pageNo;
        return url.replace("{keywords}", keywords).replace("{city}", area).replace("{offset}", pageSize.toString()).replace("{page}", pageNo.toString());
    }

    @Override
    public Integer getTotalCount(JSONObject res) {
        return res.getInteger("count");
    }

    @Override
    public void fillTable(JSONObject res) throws Exception {
        if(res.getInteger("status") == 0) {
            throw new Exception(res.getString("info"));
        }
        JSONArray results = res.getJSONArray("pois");
        if(results == null)
        {
            throw new Exception("no records");
        }

        for (Object o : results) {
            JSONObject target = (JSONObject) o;
            // 过滤排除关键字
            String name = target.getString("name");
            if(StringUtils.contains(name, exclusiveWords)) {
                continue;
            }
            // 过滤空手机号
            String tel = target.getString("tel");
            if(filterTel && (StringUtils.isEmpty(tel) || "[]".equals(tel))) {
                continue;
            }

            qrTable.getItems().add(new Company(IndexUtils.getIndex() + "", target.getString("tel"), name, target.getString("pname")+target.getString("cityname")+target.getString("adname"), target.getString("address"), target.getString("type"),
                    keywords, MapType.map.get(mapCode), target.getString("location")));

        }
    }


}
